package org.jeecg.modules.demo.soQualityOrder.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.checkOrder.entity.checkOrder;
import org.jeecg.modules.demo.checkOrder.service.IcheckOrderService;
import org.jeecg.modules.demo.soOrderDetail.entity.SoOrderDetail;
import org.jeecg.modules.demo.soOrderDetail.service.ISoOrderDetailService;
import org.jeecg.modules.demo.soQualityOrder.entity.SoQualityOrder;
import org.jeecg.modules.demo.soQualityOrder.service.ISoQualityOrderService;
import org.jeecg.modules.demo.soSaleOrder.service.ISoSaleOrderService;
import org.jeecg.modules.demo.util.generateOddUtilXs;
import org.jeecg.modules.demo.warehouseorder.entity.WarehouseOrder;
import org.jeecg.modules.demo.warehouseorder.service.IWarehouseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 销售质检单
 * @Author: jeecg-boot
 * @Date: 2021-12-06
 * @Version: V1.0
 */
@Api(tags = "销售质检单")
@RestController
@RequestMapping("/sale/soQualityOrder")
@Slf4j
public class SoQualityOrderController extends JeecgController<SoQualityOrder, ISoQualityOrderService> {
    @Autowired
    private ISoQualityOrderService soQualityOrderService;

    @Autowired
    private ISoOrderDetailService soOrderDetailService;

    @Autowired
    private IWarehouseOrderService warehouseOrderService;
    @Autowired
    private ISoSaleOrderService soSaleOrderService;
    @Autowired
    private IcheckOrderService icheckOrderService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    private static final String TITLE = "单据审核";

    private String getMessage(String name,String date) {
        String str ="由【"+name+"】于【"+date+"】发起的销售质检单需要您的审核，请及时查看！";
        return str;
    }

    /**
     * 分页列表查询
     *
     * @param soQualityOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "销售质检单-分页列表查询")
    @ApiOperation(value = "销售质检单-分页列表查询", notes = "销售质检单-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent="yunxiao/quality/SoQualityOrderList")
    public Result<?> queryPageList(SoQualityOrder soQualityOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<SoQualityOrder> queryWrapper = QueryGenerator.initQueryWrapper(soQualityOrder, req.getParameterMap());
        queryWrapper.eq("IS_DELETE", 0);
        Page<SoQualityOrder> page = new Page<SoQualityOrder>(pageNo, pageSize);
        IPage<SoQualityOrder> pageList = soQualityOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	 @PostMapping(value = "/getYkByOrder")
    public String getYkByOrder(@RequestParam(name="str",required=true)String str){
        Gson gson = new Gson();
        Map map = new HashMap();
        try{
            Map<String,Double>  map1 = soQualityOrderService.getYkByOrder(str);
            map.put("code",200);
            map.put("message","查询成功！");
            map.put("order",map1.get("DH"));
            map.put("ykje",map1.get("JE"));
            map.put("yksl",map1.get("SL"));
            String json = gson.toJson(map);
            return json;
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",500);
            map.put("message","系统错误！");
            String json = gson.toJson(map);
            return json;
        }
    }

    /**
     * 添加
     *
     * @param
     * @return
     */
    @AutoLog(value = "销售质检单-添加")
    @ApiOperation(value = "销售质检单-添加", notes = "销售质检单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody JSONObject jsonObject,HttpServletRequest req) {
        try {
            SoOrderDetail soOrderDetail = JSON.parseObject(jsonObject.toJSONString(), SoOrderDetail.class);
            SoQualityOrder sqo = JSON.parseObject(jsonObject.toJSONString(), SoQualityOrder.class);
            List<SoQualityOrder> list = this.soQualityOrderService.list();
            Collections.sort(list);

            String max_code = "";
            if (list.size() > 0) {
                max_code = list.get(0).getQoNum();
            }
            Map<String,String> codeMap = new HashMap<>();
            if(max_code == null){
                codeMap.put("maxCode",null);
            }else{
                codeMap.put("maxCode",max_code);
            }
            String tenantId = req.getHeader("tenant-id");
            String tname = soSaleOrderService.getTname(tenantId);
            String xszj = generateOddUtilXs.createCode(codeMap,tname+"ZJ_");

            sqo.setPuConNo(soOrderDetail.getSoConNo());
            sqo.setSoOrder(soOrderDetail.getSoOrder());
            sqo.setQoDate(new Date());
            sqo.setQoNum(xszj);
            sqo.setSodNo(soOrderDetail.getSodNo());
            sqo.setQoType(1);
            sqo.setChuku(0);
            sqo.setCkNum(soOrderDetail.getXclNum());
            sqo.setJldw(soOrderDetail.getJldw());
            sqo.setQoTax(soOrderDetail.getPsTax());
//			sqo.setHsdj();
//			sqo.setHsje();
//			sqo.setWsje();
//			sqo.setWsdj();
//			sqo.setJldw();
//			 sqo.setQoQuantity(0);
//			 sqo.setQoCal(0);
//			 sqo.setQoPic(Double.valueOf(0));
//			 sqo.setQoTotal(Double.valueOf(0));
//			 sqo.setQoNotax(Double.valueOf(0));
            sqo.setSoStatus(0);
            sqo.setIsDelete(0);
            soQualityOrderService.save(sqo);
            soOrderDetail.setIsQuality(1);
            soOrderDetailService.updateById(soOrderDetail);

//            SoSaleOrder sso = soSaleOrderService.getBysoNo(sqo.getSoOrder());
//            BigDecimal a = sqo.getCkNum().subtract(sqo.getQoQuantity());
//            sso.setSoLjck(sso.getSoLjck().subtract(a));
//            sso.setSoKck(sso.getSoTotail().subtract(sso.getSoLjck()));
//            if (sso.getSoLjck().compareTo(sso.getSoTotail()) > -1) {
//                sso.setIsQuality(1);
//            } else {
//                sso.setIsQuality(0);
//            }
//            soSaleOrderService.updateById(sso);



            LoginUser user = sysBaseAPI.getUserById(sqo.getSosStaff());
            TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
            templateMessageDTO.setFromUser("管理员");
            templateMessageDTO.setToUser(sqo.getShName()+",");
            templateMessageDTO.setTitle(TITLE);
            templateMessageDTO.setTemplateCode("order");
            Map<String, String> templateParam = new HashMap<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date= simpleDateFormat.format(new Date());
            templateParam.put("ts_date",date);
            templateParam.put("ts_content", getMessage(user != null?user.getRealname():"该业务员不存在！", date));
            templateParam.put("checkOrder",sqo.getQoNum());
            templateParam.put("cd_url","/yunxiao/quality/SoSaleOrderList2");
            templateMessageDTO.setTemplateParam(templateParam);
            sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);

            return Result.OK("生成质检单成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败");
        }
    }


    /**
     * 编辑
     *
     * @param soQualityOrder
     * @return
     */
    @AutoLog(value = "销售质检单-编辑")
    @ApiOperation(value = "销售质检单-编辑", notes = "销售质检单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody SoQualityOrder soQualityOrder) {
        soQualityOrderService.updateById(soQualityOrder);
        return Result.OK("编辑成功!");
    }

    //假删除
    @PutMapping(value = "/DeleteFlase")
    public Result<?> DeleteFlase(@RequestBody SoQualityOrder soQualityOrder) {
        SoOrderDetail s = soOrderDetailService.getBySodNo(soQualityOrder.getSodNo(),soQualityOrder.getSoOrder());
        if ("1".equals(soQualityOrder.getIsShjl())) {
            WarehouseOrder ws = warehouseOrderService.getByRkNo(s.getRkNo());
            BigDecimal a = soQualityOrder.getCkNum().subtract(soQualityOrder.getQoQuantity());
//			 ws.setStandingstock(ws.getStandingstock().add(soQualityOrder.getQoQuantity()));
            ws.setStandingstock(ws.getStandingstock().subtract(a));
            warehouseOrderService.updateById(ws);
        }
        s.setIsQuality(0);
        soOrderDetailService.updateById(s);
//        SoSaleOrder sso = soSaleOrderService.getBysoNo(s.getSoOrder());
//        BigDecimal a = soQualityOrder.getCkNum().subtract(soQualityOrder.getQoQuantity());
//        sso.setSoLjck(sso.getSoLjck().add(a));
//        sso.setSoKck(sso.getSoTotail().subtract(sso.getSoLjck()));
//        if (sso.getSoLjck().compareTo(sso.getSoTotail()) > -1) {
//            sso.setIsQuality(1);
//        } else {
//            sso.setIsQuality(0);
//        }
//        soSaleOrderService.updateById(sso);
        soQualityOrderService.removeById(soQualityOrder);
        return Result.OK("删除成功!");
    }

    //审核
    @PutMapping(value = "/editShenhe")
    public Result<?> editShenhe(@RequestBody SoQualityOrder soQualityOrder) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<checkOrder> orders = icheckOrderService.getByWhNum(soQualityOrder.getWhNum());
        if(!orders.isEmpty()){
            return Result.error(300,"仓库正在盘点，无法审核！");
        }
        if (!soQualityOrder.getShName().equals(sysUser.getId())) {
            return Result.error(500,"您不是当前单据的指定审核人！");
        }
        if (soQualityOrder.getSoStatus() == 0) {
//            soQualityOrder.setShName("");
            soQualityOrder.setShTime(null);
        }else {
//            soQualityOrder.setShName(sysUser.getRealname());
            soQualityOrder.setShTime(new Date());
        }
//        if (soQualityOrder.getIsShjl() == "" || soQualityOrder.getIsShjl() == null){
//            SoOrderDetail s = soOrderDetailService.getBySodNo(soQualityOrder.getSodNo(),soQualityOrder.getSoOrder());
//            if(s.getRkNo().contains(",")){
//                String[] strs = s.getRkNo().split(",");
//                for (String str : strs) {
//                    WarehouseOrder ws = warehouseOrderService.getByRkNo(str);
//                    BigDecimal a = soQualityOrder.getCkNum().subtract(soQualityOrder.getQoQuantity());
//
//                    ws.setStandingstock(ws.getStandingstock().add(a));
//                    if (ws.getStandingstock().compareTo(BigDecimal.valueOf(0)) == -1){
//                        ws.setStandingstock(BigDecimal.valueOf(0.00));
//                    }
//                    warehouseOrderService.updateById(ws);
//                }
//            }else{
//                WarehouseOrder ws = warehouseOrderService.getByRkNo(s.getRkNo());
//                BigDecimal a = soQualityOrder.getCkNum().subtract(soQualityOrder.getQoQuantity());
//
//                ws.setStandingstock(ws.getStandingstock().add(a));
//                if (ws.getStandingstock().compareTo(BigDecimal.valueOf(0)) == -1){
//                    ws.setStandingstock(BigDecimal.valueOf(0.00));
//                }
//                warehouseOrderService.updateById(ws);
//            }
//            soQualityOrder.setIsShjl("1");
//        }
        soQualityOrderService.updateById(soQualityOrder);

//		 SoSaleOrder sso = soSaleOrderService.getBysoNo(s.getSoOrder());
//		 sso.setSoLjck(sso.getSoLjck().add(soQualityOrder.getQoQuantity()));
//		 sso.setSoKck(sso.getSoTotail().subtract(sso.getSoLjck()));
//		 soSaleOrderService.updateById(sso);

        return Result.OK("审核成功!");
    }

    //通过id查询质检数量
    @GetMapping(value = "/getQuantity")
    public Result<?> getQuantity(@RequestParam(name = "id", required = true) String id) {
        SoQualityOrder sqo = soQualityOrderService.getQuantityById(id);
        return Result.OK(sqo);
    }

    //新增质检单时查询已生成的质检单
    @GetMapping(value = "/zhijianBySoq")
    public Result<?> queryBySoNo(@RequestParam(name = "id", required = true) String id) {
        List<SoQualityOrder> soq = soQualityOrderService.getBysoNo(id);
        return Result.OK(soq);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "销售质检单-通过id删除")
    @ApiOperation(value = "销售质检单-通过id删除", notes = "销售质检单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        soQualityOrderService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "销售质检单-批量删除")
    @ApiOperation(value = "销售质检单-批量删除", notes = "销售质检单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.soQualityOrderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "销售质检单-通过id查询")
    @ApiOperation(value = "销售质检单-通过id查询", notes = "销售质检单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        SoQualityOrder soQualityOrder = soQualityOrderService.getById(id);
        if (soQualityOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(soQualityOrder);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param soQualityOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SoQualityOrder soQualityOrder) {
        return super.exportXls(request, soQualityOrder, SoQualityOrder.class, "销售质检单");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SoQualityOrder.class);
    }

}
